package org.jwcloud.project.module.zx.template.service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jwcloud.project.module.zx.common.Resp;
import org.jwcloud.project.module.zx.common.repository.RptCommonRepository;
import org.jwcloud.project.module.zx.common.service.RptUtService;
import org.jwcloud.project.module.zx.template.service.repository.RptTemplateRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.jw.mid.mm.comm.common.controller.BaseController;
import com.jw.mid.mm.comm.common.json.Response;
import com.jw.mid.mm.comm.common.pagination.ListBounds;
import com.jw.mid.mm.comm.common.pagination.ListSlice;
import com.jw.mid.mm.comm.common.pagination.PageListSlice;
import com.jw.mid.mm.comm.common.pagination.Pagination;

import io.swagger.annotations.ApiImplicitParam;

@Service
@Transactional
public class RptTemplateServiceImpl extends BaseController implements RptTemplateService{
	
//	@Autowired
//    public RptCommonRepository rptCommonRepository;
	 
	@Autowired
    public RptTemplateRepository rptTemplateRepository;
	
	@Autowired
    public RptUtService rptUtService;
	
	@Override
	public Resp<Object> doTemplateInsert(Map param) {
		// TODO Auto-generated method stub
		String flag = this.rptTemplateRepository.checkTemplate(param);
		if(!StringUtils.isEmpty(flag)) {
			return Resp.error(flag);
		}
		return Resp.success(rptTemplateRepository.doTemplateInsert(param));
	}

	@Override
	public Resp<Object> doTemplateUpdate(Map param) {
		// TODO Auto-generated method stub
		String flag = this.rptTemplateRepository.checkTemplate(param);
		if(!StringUtils.isEmpty(flag)) {
			return Resp.error(flag);
		}
		return Resp.success(rptTemplateRepository.doTemplateUpdate(param));
	}

	@Override
	public Resp<Object> doTemplateDelete(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(rptTemplateRepository.doTemplateDelete(param));
	}

	@Override
	/**
	 * 复制模板
	 * 
	 * return 新模板id
	 */
	public Resp<Object> doTemplateCopy(Map param) {
		// TODO Auto-generated method stub
		
		String flag = this.rptTemplateRepository.checkTemplate_copy(param);
		if(!StringUtils.isEmpty(flag)) {
			return Resp.error(flag);
		}
		
		param.put("new_template_id", "-1");
//		param.put("_session_user", "-11");
//		param.put("_session_dept", "-12");
//		param.put("_session_org", "-13");
		System.out.println(param);
		try {
			this.rptTemplateRepository.doTemplateCopy(param);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("prod is exception...........");
		}
		
		System.out.println(param);
		return Resp.success(param.get("new_template_id"));
	}

	@Override
	public Resp<Object> doTemplateSetStart(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(rptTemplateRepository.doTemplateSetStart(param));
	}

	@Override
	public Resp<List<Map<String, String>>> queryTemplateList(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(rptTemplateRepository.queryTemplateList(param));
	}
	
	@Override
	public Resp<Response<PageListSlice>> queryTemplateList(Pagination pagination, Map params) {
		// TODO Auto-generated method stub
		//分页
		pagiBuild(pagination, params);
		
		//System.out.println("after build: " + params);
        return Resp.success(this.rptUtService.findPagi(
    		pagination,
    		params,
    		this.rptTemplateRepository.queryTemplateList(params), 
    		this.rptTemplateRepository.queryTemplateList_total(params)
    	));
	}

	@Override
	public Resp<List<Map<String, String>>> queryWorkList(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(this.rptTemplateRepository.queryWorkList(param));
	}
	@Override
	public Resp<List<Map<String, String>>> queryPriorWorkList(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(this.rptTemplateRepository.queryPriorWorkList(param));
	}

	@Override
	public Resp<Object> doWorkInsert(Map param) {
		// TODO Auto-generated method stub
//		this.rptTemplateRepository.doWorkInsert(param);
//		return this.rptTemplateRepository.doTemplateWorkInsert(param);
		String flag = this.rptTemplateRepository.checkWork(param);
		if(!StringUtils.isEmpty(flag) ) {
			return Resp.error(flag);
		}
		return Resp.success(this.rptTemplateRepository.doWorkInsert(param));
		
//		String parentWorkIdStr = (String) param.get("parentWorkIdStr");
//		String[] strs = parentWorkIdStr.split(";");
//		for(String temp: strs) {
//			param.put("parent_work_id", temp);
//			this.rptTemplateRepository.doWorkInsert_rel(param);
//		}
//		return param;
	}
	
	public static Map commonInsertResult(int updateNum, Map param) {
		Map<String, String> map = new HashMap();
		map.put("updateNum", updateNum + "");
		map.put("new_id_", param.get("new_id_") + "");
		return map;
	}

	@Override
	public Resp<Object> doWorkUpdate(Map param) {
		// TODO Auto-generated method stub
//		System.out.println("---------" + param);
		String flag = this.rptTemplateRepository.checkWork(param);
		if(!StringUtils.isEmpty(flag) ) {
			return Resp.error(flag);
		}
		return Resp.success(this.rptTemplateRepository.doWorkUpdate(param));
	}

	@Override
	public Resp<Object> doWorkDelete(Map param) {
		// TODO Auto-generated method stub 
		int row = this.rptTemplateRepository.doWorkDelete(param);
		if(row == 0) {
			return Resp.error("该工作已成为某一工作的前置工作，无法删除");
		}else {
			return Resp.success(1);
		}
//		return Resp.success(this.rptTemplateRepository.doWorkDelete(param));
	}

	@Override
	public Resp<Object> doWorkInsertPrior(Map param) {
		// TODO Auto-generated method stub
		String priorIds = (String) param.get("priorIds");
//		if(StringUtils.isEmpty(priorIds)) {
//			return Resp.error("参数为空");
//		}
		this.rptTemplateRepository.doWorkDeletePrior_log(param);
		this.rptTemplateRepository.doWorkDeletePrior(param);
		
		if(!StringUtils.isEmpty(priorIds)) {
			for(String prior: priorIds.split(";")) {
				param.put("parent_work_id", prior);
				this.rptTemplateRepository.doWorkInsertPrior(param);
			}
		}
		
		Map<String, String> daoMap = new HashMap();
		List<Map<String, String>> allPriorInfo = this.rptTemplateRepository.queryWorkRelList_byTemplate(daoMap);
		
		//checkWorkLoop((String) param.get("id"), allPriorInfo);
		
		return Resp.success();
	}
	
	private void checkWorkLoop(String work_id, List<Map<String, String>> allPriorInfo) {
		if(allPriorInfo != null && allPriorInfo.size() > 0) {
			return;
		}
		
		for(int i = 0; i < allPriorInfo.size(); i++) {
			if(allPriorInfo.get(i).get("work_id").equals(work_id)) {
				//do check
				Set<String> set = new HashSet();
				set.add(allPriorInfo.get(i).get("work_id"));
				if(!set.add(allPriorInfo.get(i).get("parent_work_id"))) {
					throw new RuntimeException("work loop");
				}
				
				_loopCheck(work_id, allPriorInfo, set);
				set = new HashSet();
			}
		}
	}
	
	private void _loopCheck(String work_id, List<Map<String, String>> allPriorInfo, Set<String> loopSet) {
		for(int i = 0; i < allPriorInfo.size(); i++) {
			if(allPriorInfo.get(i).get("work_id").equals(work_id)) {
				//do check
				if(!loopSet.add(allPriorInfo.get(i).get("parent_work_id"))) {
					throw new RuntimeException("work loop");
				}
				
				_loopCheck(allPriorInfo.get(i).get("parent_work_id"), allPriorInfo, loopSet);
			}
		}
	}
	
	@Override
	public Resp<Object> changeTaskIndex(Map param) {
		// TODO Auto-generated method stub
		Map daoMap = new HashMap();
		daoMap.put("id", param.get("qian_id"));
		daoMap.put("ord", param.get("qian_idx"));
		this.rptTemplateRepository.updateTask(daoMap);
		
		daoMap.put("id", param.get("hou_id"));
		daoMap.put("ord", param.get("hou_idx"));
		return Resp.success(this.rptTemplateRepository.updateTask(daoMap));
	}
	
	@Override
	public Resp<Object> updateTask(Map param) {
		// TODO Auto-generated method stub
		int res = this.rptTemplateRepository.updateTask(param);
		//return Resp.success(this.rptTemplateRepository.updateTask(param));
		
		
		
		param.put("this_rel_task_id", param.get("id"));
		
		this.rptTemplateRepository.deleteTaskSpPerson(param);
		
//		String sp_person = (String) param.get("sp_person");
//		String sp_person_name = (String) param.get("sp_person_name");
//		String sp_level = (String) param.get("sp_level");
		
		
		String sp_person = (String) param.get("sp_person_id");
		String sp_person_name = (String) param.get("sp_person_name");
		String sp_level = (String) param.get("sp_level");
		
		String person_dept = (String) param.get("sp_dept_id");
		String person_dept_name = (String) param.get("sp_dept_name");
		
		
		if(StringUtils.isEmpty(sp_person)) {
			return Resp.success(res);
		}
		
		
		
		String[] _sp_person = sp_person.split(";");
		String[] _sp_person_name = sp_person_name.split(";");
		String[] _sp_level = sp_level.split(";");
		String[] _person_dept = person_dept.split(";");
		String[] _person_dept_name = person_dept_name.split(";");
		
		for(int i = 0; i < _sp_person.length; i++) {
			param.put("this_person_id", _sp_person[i]);
			param.put("this_person_name", _sp_person_name[i]);
			param.put("this_sp_level", _sp_level[i]);
			param.put("this_person_dept", _person_dept[i]);
			param.put("this_person_dept_name", _person_dept_name[i]);
			this.rptTemplateRepository.insertTask_spPerson(param);
		}
		
		
		
		
//		String[] _sp_person = sp_person.split(";");
//		String[] _sp_person_name = sp_person_name.split(";");
//		String[] _sp_level = sp_level.split(";");
//		
//		for(int i = 0; i < _sp_person.length; i++) {
//			param.put("this_person_id", _sp_person[i]);
//			param.put("this_person_name", _sp_person_name[i]);
//			param.put("this_sp_level", _sp_level[i]);
//			this.rptTemplateRepository.insertTask_spPerson(param);
//		}
		
		return Resp.success(res);
	}
	
	@Override
	public Resp<List<Map<String, String>>> queryTaskList(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(this.rptTemplateRepository.queryTaskList(param));
	}
	@Override
	public Resp<List<Map<String, Object>>> queryItemList_sz(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(this.rptTemplateRepository.queryItemList_sz(param));
	}
	@Override
	public Resp<List<Map<String, Object>>> queryTaskList_sz_rel_template(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(this.rptTemplateRepository.queryTaskList_sz_rel_template(param));
	}
	
	@Override
	public Resp<Response<PageListSlice>> queryItemList_sz(Pagination pagination, Map param) {
		// TODO Auto-generated method stub
//		return this.rptTemplateRepository.queryTaskList_sz(param);
		pagiBuild(pagination, param);
		return Resp.success(this.rptUtService.findPagi(
    		pagination,
    		param,
    		this.rptTemplateRepository.queryItemList_sz(param), 
    		this.rptTemplateRepository.queryItemList_sz_total(param)
    	));
	}
	
	@Override
	public Resp<Response<PageListSlice>> queryTaskList_sz(Pagination pagination, Map param) {
		// TODO Auto-generated method stub
//		return this.rptTemplateRepository.queryTaskList_sz(param);
		pagiBuild(pagination, param);
		
		Response<PageListSlice> res = this.rptUtService.findPagi(
	    		pagination,
	    		param,
	    		this.rptTemplateRepository.queryTaskList_sz(param), 
	    		this.rptTemplateRepository.queryTaskList_sz_total(param)
	    	);
		
		List<Map<String, Object>> list = res.getPayload().getList();
		Map daoMap = new HashMap();
		for(Map<String, Object> map: list) {
			daoMap.put("id", map.get("id"));
			map.put("templateList", this.rptTemplateRepository.queryTaskList_sz_rel_template(daoMap));
		}
		
		return Resp.success(res);
	}
	
	@Override
	public Resp<Object> queryTaskList_sz_unpagi(Map param) {
		// TODO Auto-generated method stub
//		return this.rptTemplateRepository.queryTaskList_sz(param);
		return Resp.success(this.rptTemplateRepository.queryTaskList_sz(param));
	}

	@Override
	public Resp<Integer> insertTask(Map param) {
		// TODO Auto-generated method stub
		
		int res = this.rptTemplateRepository.insertTask(param);
		param.put("this_rel_task_id", param.get("new_id_"));
		
		String sp_person = (String) param.get("sp_person_id");
		String sp_person_name = (String) param.get("sp_person_name");
		String sp_level = (String) param.get("sp_level");
		
		String person_dept = (String) param.get("sp_dept_id");
		String person_dept_name = (String) param.get("sp_dept_name");
		
		if(StringUtils.isEmpty(sp_person)) {
			return Resp.success(res);
		}
		
		String[] _sp_person = sp_person.split(";");
		String[] _sp_person_name = sp_person_name.split(";");
		String[] _sp_level = sp_level.split(";");
		String[] _person_dept = person_dept.split(";");
		String[] _person_dept_name = person_dept_name.split(";");
		
		for(int i = 0; i < _sp_person.length; i++) {
			param.put("this_person_id", _sp_person[i]);
			param.put("this_person_name", _sp_person_name[i]);
			param.put("this_sp_level", _sp_level[i]);
			param.put("this_person_dept", _person_dept[i]);
			param.put("this_person_dept_name", _person_dept_name[i]);
			this.rptTemplateRepository.insertTask_spPerson(param);
		}
		
//    	@ApiImplicitParam(name = "sp_person", value = "审批人 aa;ss;dd", required = false, dataType = "string", paramType = "query"),
//    	@ApiImplicitParam(name = "sp_person_name", value = "审批人名字", required = false, dataType = "string", paramType = "query"),
//    	@ApiImplicitParam(name = "sp_level"
		
//		int res = this.rptTemplateRepository.insertTask(param);
//		String item_name = (String) param.get("item_name");
//		String item_content = (String) param.get("item_content");
//		
//		if(StringUtils.isEmpty(item_name)) {
//			return res;
//		}
//		
//		String[] item_name_ = item_name.split(";");
//		String[] item_content_ = item_content.split(";");
//		
//		param.put("task_id", param.get("new_id_"));
//		
//		for(int i = 0; i < item_name_.length; i++) {
//			this.rptTemplateRepository.insertItem(param);
//		}
		
		return Resp.success(res);
	}

	@Override
	public Resp<Integer> insertTask_sz(Map param) {
		// TODO Auto-generated method stub
		
		String item_code = (String) param.get("item_code");
		String upload_type = (String) param.get("upload_type");
		
		if(!StringUtils.isEmpty(item_code)) {
			String[] check_item_code =item_code.split(";");
			boolean itemCheck = true;
			a: for(int i = 0; i < check_item_code.length; i++) {
				for(int j = i + 1; j < check_item_code.length; j++) {
					if(check_item_code[j].equals(check_item_code[i])) {
						itemCheck = false;
						break a;
					}
				}
			}
			if(itemCheck == false) {
				return Resp.error("要件不可重复");
			}
		}
		
		String flag = this.rptTemplateRepository.checkTask_sz(param);
		if(!StringUtils.isEmpty(flag)) {
			return Resp.error(flag);
		}
		
		int res = this.rptTemplateRepository.insertTask_sz(param);
//		String item_name = (String) param.get("item_name");
//		String item_content = (String) param.get("item_content");
//		String item_code = (String) param.get("item_code");
//		String upload_type = (String) param.get("upload_type");
		
		
		if(StringUtils.isEmpty(item_code)) {
			return Resp.success(res);
		}
		
//		String[] item_name_ = item_name.split(";");
//		String[] item_content_ = item_content.split(";");
		String[] item_id_ = item_code.split(";");
		String[] upload_type_ = upload_type.split(";");
		
		param.put("task_id", param.get("new_id_"));
		
		for(int i = 0; i < item_id_.length; i++) {
//			param.put("this_item_name", item_name_[i]);
//			param.put("this_item_content", item_content_[i]);
//			this.rptTemplateRepository.insertItem_sz(param);
			param.put("this_item_id", item_id_[i]);
			param.put("this_upload_type", upload_type_[i]);
			this.rptTemplateRepository.insertItemTask_sz(param);
		}
		
		return Resp.success(res);
	}
	
	
	@Override
	public Resp<Object> updateTask_sz(Map param) {
		// TODO Auto-generated method stub
		
		String item_code = (String) param.get("item_code");
		String upload_type = (String) param.get("upload_type");
		
		if(!StringUtils.isEmpty(item_code)) {
			String[] check_item_code =item_code.split(";");
			boolean itemCheck = true;
			a: for(int i = 0; i < check_item_code.length; i++) {
				for(int j = i + 1; j < check_item_code.length; j++) {
					if(check_item_code[j].equals(check_item_code[i])) {
						itemCheck = false;
						break a;
					}
				}
			}
			if(itemCheck == false) {
				return Resp.error("要件不可重复");
			}
		}
		
		String flag = this.rptTemplateRepository.checkTask_sz(param);
		if(!StringUtils.isEmpty(flag)) {
			return Resp.error(flag);
		}
		
		int res = this.rptTemplateRepository.updateTask_sz(param);
		
		if(StringUtils.isEmpty(item_code)) {
			return Resp.success(res);
		}
		
		String[] item_id_ = item_code.split(";");
		String[] upload_type_ = upload_type.split(";");
		
		param.put("task_id", param.get("id"));
		
		this.rptTemplateRepository.deleteItem_sz_byTask(param);
		
		for(int i = 0; i < item_id_.length; i++) {
			param.put("this_item_id", item_id_[i]);
			param.put("this_upload_type", upload_type_[i]);
			this.rptTemplateRepository.insertItemTask_sz(param);
		}
		
		return Resp.success(res);
	}
	

	@Override
	public Resp<Integer> deleteTask(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(this.rptTemplateRepository.deleteTask(param));
	}

	@Override
	public Resp<Integer> deleteTask_sz(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(this.rptTemplateRepository.deleteTask_sz(param));
	}

	@Override
	public Resp<Integer> deleteItem(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(this.rptTemplateRepository.deleteItem(param));
	}

	@Override
	public Resp<Integer> deleteItem_sz(Map param) {
		// TODO Auto-generated method stub
		return Resp.success(this.rptTemplateRepository.deleteItem_sz(param));
	}

//	@Override
//	public int insertItem(Map param) {
//		// TODO Auto-generated method stub
//		return this.rptTemplateRepository.insertItem(param);
//	}
//
	@Override
	public Resp<Object> insertItem_sz(Map param) {
		// TODO Auto-generated method stub
		String flag = this.rptTemplateRepository.checkItem_sz(param);
		if(!StringUtils.isEmpty(flag)) {
			return Resp.error(flag);
		}
		int res = this.rptTemplateRepository.insertItem_sz(param);
		String colName = (String) param.get("col_name");
		String colType = (String) param.get("col_type");
		if(StringUtils.isEmpty(colName) || StringUtils.isEmpty(colType)) {
			return Resp.success(res);
		}
		param.put("item_id_", param.get("new_id_"));
		String[] cName = colName.split(";");
		String[] cType = colType.split(";");
		for(int i = 0; i < cName.length; i++) {
			param.put("col_name", cName[i]);
			param.put("col_type", cType[i]);
			this.rptTemplateRepository.insertCol(param);
		}
		
		return Resp.success(res);
	}
	@Override
	public Resp<Object> updateItem_sz(Map param) {
		// TODO Auto-generated method stub
		//String flag = this.rptTemplateRepository.checkItem_sz(param);
//		if(!StringUtils.isEmpty(flag)) {
//			return Resp.error(flag);
//		}
		String flag = this.rptTemplateRepository.checkItem_sz(param);
		if(!StringUtils.isEmpty(flag)) {
			return Resp.error(flag);
		}
		int res = this.rptTemplateRepository.updateItem_sz(param);
		String colName = (String) param.get("col_name");
		String colType = (String) param.get("col_type");
		this.rptTemplateRepository.deleteCol(param);
		if(StringUtils.isEmpty(colName) || StringUtils.isEmpty(colType)) {
			return Resp.success(res);
		}
		param.put("item_id_", param.get("id"));
		String[] cName = colName.split(";");
		String[] cType = colType.split(";");
		for(int i = 0; i < cName.length; i++) {
			param.put("col_name", cName[i]);
			param.put("col_type", cType[i]);
			this.rptTemplateRepository.insertCol(param);
		}
		
		return Resp.success(res);
	}
	/**
	 * 临时   之后改切片、pagehelper
	 * @param map
	 */
	private void pagiBuild(Pagination pagination, Map<String, String> map) {
		String pagisize = map.get("pageSize");
		String currentPage = map.get("currentPage");
		if(StringUtils.isEmpty(pagisize) || StringUtils.isEmpty(currentPage)) {
			return;
		}
		int ipagisize = Integer.valueOf(pagisize);
		int icurrentPage = Integer.valueOf(currentPage);
		map.put("_length", pagisize);
		int start = (icurrentPage - 0) * ipagisize;
		map.put("_start", start + "");
		pagination.setCurrentPage(icurrentPage);
		pagination.setPageSize(ipagisize);
	}

}
